package com.rongshu.sendmessage.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.KeFuBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.ProgressDialog;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;

import java.util.HashMap;
import java.util.Map;

import static com.rongshu.sendmessage.util.DialogUtil.hideProgress;

public class KeFuActivity extends BaseActivity {

    private static final int REQUEST_CALL_PERMISSION = 14;
    private ProgressDialog dialog;
    private TextView tv_work_time;
    private String phone="15532131001";
    private String weixinId="kf_ylzx";
    private TextView tv_content;
    private ImageView iv_ewm;
    private String serviceHours;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ke_fu);
        mContext=this;
        tv_content=findViewById(R.id.tv_content);
        findViewById(R.id.titleLayLeft).setOnClickListener(view->{
            finish();
        });
        TextView title = findViewById(R.id.title);
        title.setText("联系客服");
        View titleLayRight = findViewById(R.id.titleLayRight);
        titleLayRight.setVisibility(View.GONE);
        tv_work_time=findViewById(R.id.tv_work_time);
        iv_ewm=findViewById(R.id.iv_ewm);
//        initData();

        phone=MyApplication.mSettings.getString(HYContent.CustomerNumber,"15532131001");
        weixinId=MyApplication.mSettings.getString(HYContent.CustomerWxNum,"kf_ylzx");
        serviceHours=MyApplication.mSettings.getString(HYContent.ServiceHours,"8:30-18:00(工作日)");
        tv_work_time.setText("工作时间："+serviceHours);
        String serviceQrCode = MyApplication.mSettings.getString(HYContent.ServiceQrCode, "");
        ImageLoader.getInstance().displayImage(serviceQrCode,iv_ewm);
    }


    public void onClick(View view) {
        if (view.getId()==R.id.btn_call){
            if (checkReadPermission(Manifest.permission.CALL_PHONE, REQUEST_CALL_PERMISSION)) {
                call();
            }

        }else if (view.getId()==R.id.tbn_jump_weixin){
//            复制信息
            //获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", weixinId);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
//            跳转至微信
            try {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(cmp);
                startActivity(intent);
                ToastUtils.show(mContext,"快去添加好友页面粘贴添加客服吧");
            } catch (ActivityNotFoundException e) {
                // TODO: handle exception
                Toast.makeText(this, "检查到您手机没有安装微信，请安装后使用该功能", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @SuppressLint("MissingPermission")
    private void call(){
        if(StringUtils.isEmpty(phone)){
            ToastUtils.show(mContext,"未获取到客服电话");
            return;
        }
        String replace = phone.replace("(", "");
        replace = replace.replace(")", "");
        replace = replace.replace("-", "");
        String finalReplace = replace;
        DialogUtil.showConfirmDialog(mContext, "提示", "您确定给" + phone + "打电话吗?", new DialogUtil.OnDialogListener<Void>() {
            @Override
            public void onPositiveButtonClick(Void aVoid) {
                Intent intent =  new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + finalReplace));//直接拨打电话
                startActivity(intent);
            }

            @Override
            public void onNegativeButtonClick(Void aVoid) {

            }
        });
    }
    /**
     * 判断是否有某项权限
     * @param string_permission 权限
     * @param request_code 请求码
     * @return
     */
    public boolean checkReadPermission(String string_permission, int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(mContext, string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(KeFuActivity.this, new String[]{string_permission}, request_code);
        }
        return flag;
    }

    /**
     * 检查权限后的回调
     * @param requestCode 请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CALL_PERMISSION: //拨打电话
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(mContext,"请允许拨号权限后再试", Toast.LENGTH_SHORT).show();
                } else {//成功
                    call();
                }
                break;
        }
    }
    public void showProgress() {
        dialog = ProgressDialog.createDialog(mContext);
        dialog.show();
    }

    public void hideProgress() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }
//    private void initData() {
//        showProgress();
//        Map<String, String> param = new HashMap<>();
//        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
//        //获取客服信息
//        OkGo.<String>post(new HYContent().KE_FU_URL).params(param).tag("KE_FU_URL").execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//                hideProgress();
//                IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
//                final int code = jr.getCode();
//                if (code > 0) {
//                    try {
//
//                        JSONArray ms = jr.getJSONArrayData();
//                        if(ms!=null) {
//                            KeFuBean keFuBean= JSON.parseObject(JSON.toJSONString(ms), KeFuBean.class);
//                            tv_work_time.setText(keFuBean.getServiceTime());
//                            tv_content.setText(keFuBean.getContent());
//
//                            tv_work_time.setText(keFuBean.getServiceTime());
//                            tv_content.setText(keFuBean.getContent());
//                        }else{
//                            ToastUtils.show(mContext,jr.getMsg());
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//            @Override
//            public void onError(Response<String> response) {
//                hideProgress();
//            }
//        });
//
//
//    }
}